import {
	IDENTITY_PERSISTENT_KEY,
	ROLES_KEY,
	ACCESS_TOKEN_KEY,
	TOKEN_KEY,
	USER_INFO_KEY
} from '@/enums/cacheEnum';
import {
	token as tokenApi,
	phoneToken,
  authorizationToken,
	setOrganization,
	checkLogin,
	logout,
	profile,
	profileEdit,
	changePassword,
	changeUserEmail,
	changeUserPhone,
} from '@/apis/identity';
import {
	getAuthInfo
} from '@/apis/authorization';
import headerImg from '@/static/images/avatar/header.png';

export const state = {
	/** 身份持久化 */
	identityPersistent: null,
	/** 用户信息 */
	userInfo: null,
	/** 访问令牌 */
	accessToken: undefined,
	/** JwtToken对象 */
	token: null,
	/** 角色列表 */
	roleList: [],
	/** 最后刷新时间 */
	lastUpdateTime: 0,
	/** SignalR集线器的连接 */
	signalrHub: null,
}

/** 获取器 */
export const getters = {
	/** 是否登陆 */
	hasLogin: (state, getters, dispatch) => {
		// console.log('hasLogin',getters);
		let accessToken = getters.getAccessToken;
		const token = getters.getToken;
		// console.log(accessToken);
		// console.log(token);
		if (!accessToken && token && token.AccessToken) {
			accessToken = token.AccessToken;
		}
		if (accessToken && token && token.AccessTokenExpiresUtc) {
			return true;
			// // TODO:判断刷新令牌是否已过期
			// const diff = Math.round((token.AccessTokenExpiresUtc - new Date().valueOf()) / 1000);
			// console.log(diff);
			// if (diff <= 0) {
			// 	// // TODO:刷新Token
			// 	// const userInfo = await dispatch('refreshToken', refreshToken, mode);
			// 	// if (userInfo) {
			// 	// 	return true;
			// 	// }
			// 	return false;
			// } else {
			// 	return true;
			// }
		} else {
			return false;
		}
	},
	/** 获取身份持久化信息 */
	getIdentityPersistent: state => {
		// console.log('getIdentityPersistent1', state.identityPersistent);
		if (state.identityPersistent !== undefined && state.identityPersistent !== null && state
			.identityPersistent !== '') {
			return state.identityPersistent;
		}
		const identityPersistent = uni.getStorageSync(IDENTITY_PERSISTENT_KEY);
		if (identityPersistent !== undefined && identityPersistent !== null && identityPersistent !== '') {
			return identityPersistent;
		}
		return true;
	},
	/** 获取用户信息 */
	getUserInfo: state => {
		if (state.userInfo) {
			return state.userInfo;
		}
		const userInfo = uni.getStorageSync(USER_INFO_KEY);
		if (userInfo) {
			return userInfo;
		}
		return {};
	},
	/** 获取AccessToken */
	getAccessToken: state => {
		if (state.accessToken) {
			return state.accessToken;
		}
		const accessToken = uni.getStorageSync(ACCESS_TOKEN_KEY);
		if (accessToken) {
			return accessToken;
		}
		return '';
	},
	/** 获取JwtToken对象 */
	getToken: state => {
		if (state.token) {
			return state.token;
		}
		const token = uni.getStorageSync(TOKEN_KEY);
		if (token) {
			return token;
		}
		return {};
	},
	/** 获取角色列表 */
	getRoleList: state => {
		if (state.roleList && state.roleList.length > 0) {
			return state.roleList;
		}
		const cacheRoleList = uni.getStorageSync(ROLES_KEY);
		if (cacheRoleList && cacheRoleList.length > 0) {
			return cacheRoleList;
		}
		return [];
	},
	/** 获取最后刷新时间 */
	getLastUpdateTime: state => {
		return state.lastUpdateTime;
	},
	/** 获取SignalR集线器的连接 */
	getSignalRHub: state => {
		return state.signalrHub;
	},
}

/** 方法 */
export const actions = {
	/** 设置身份持久化信息 */
	setIdentityPersistent: function({
		state,
		commit,
		dispatch
	}, persistent) {
		// console.log('setIdentityPersistent', persistent);
		// uni.removeStorageSync(IDENTITY_PERSISTENT_KEY);
		state.identityPersistent = persistent;
		uni.setStorageSync(IDENTITY_PERSISTENT_KEY, persistent);
	},
	/** 设置用户信息 */
	setUserInfo: function({
		state,
		commit,
		getters,
		dispatch
	}, userInfo) {
		// uni.removeStorageSync(USER_INFO_KEY);
		state.userInfo = userInfo;
		state.lastUpdateTime = new Date().getTime();
		if (getters.getIdentityPersistent === true) {
			uni.setStorageSync(USER_INFO_KEY, userInfo);
		}
	},
	/**
	 * 设置JwtToken
	 * @param token JwtToken模型
   * @param refresh 是否刷新用户
	 */
	setToken: async function({
		state,
		commit,
		getters,
		dispatch
	}, token, refresh = true) {
		if (token) {
			state.accessToken = token.AccessToken;
			if (getters.getIdentityPersistent === true) {
				uni.setStorageSync(ACCESS_TOKEN_KEY, token.AccessToken);
			}
			let seconds = new Date().valueOf();
			seconds = Math.round((token.RefreshTokenExpiresUtc - seconds) / 1000);
			if (seconds > 0) {
				state.token = token;
				if (getters.getIdentityPersistent === true) {
					uni.setStorageSync(TOKEN_KEY, token);
				}
			}
      if(refresh){
        await dispatch('refreshUser');
      }
		} else {
      await dispatch('resetIdentityState');
    }
	},
	/** 设置角色列表 */
	setRoleList: function({
		state,
		commit,
		getters,
		dispatch
	}, roleList) {
		// uni.removeStorageSync(ROLES_KEY);
		state.roleList = roleList;
		if (getters.getIdentityPersistent === true) {
			uni.setStorageSync(ROLES_KEY, roleList);
		}
	},
	/** 重置身份认证状态 */
	resetIdentityState: async function({
		state,
		commit,
		dispatch
	}) {
		state.accessToken = '';
		uni.removeStorageSync(ACCESS_TOKEN_KEY);

		state.token = null;
		uni.removeStorageSync(TOKEN_KEY);

		state.userInfo = null;
		uni.removeStorageSync(USER_INFO_KEY);

		state.roleList = [];
		uni.removeStorageSync(ROLES_KEY);

		// removePreferenceInfo({
		// 	commit,
		// 	state
		// });
		await dispatch('refreshUser');
		await dispatch('disconnectSignalRHub');
	},
	/**
	 * @description: 登录（login）
	 */
	login: async function({
		state,
		commit,
		dispatch
	}, {
		params,
		goHome,
		mode
	}) {
		// console.log(params);
		try {
			const result = await tokenApi(params, mode);
			// console.log('login', result);
			if (result.Data) {
				const token = result.Data;
				await dispatch('loginEnd', token);
				// console.log('login',{ params, goHome, mode});
				return await dispatch('afterLoginAction', goHome);
			}
			return null;
		} catch (error) {
			return Promise.reject(error);
		}
	},
	/**
	 * @description: 使用手机号码登录
	 */
	phoneLogin: async function({
		state,
		commit,
		dispatch
	}, {
		params,
		goHome,
		mode
	}) {
		try {
			const result = await phoneToken(params, mode);
			// console.log('phoneLogin',result);
			if (result.Data) {
				const token = result.Data;
				await dispatch('loginEnd', token);

				return await dispatch('afterLoginAction', goHome);
			}
			return null;
		} catch (error) {
			return Promise.reject(error);
		}
	},
  /**
   * @description: 使用授权码登录
   */
  authorizationLogin: async function({
  	state,
  	commit,
  	dispatch
  }, {
  	params,
  	goHome,
  	mode
  }) {
  	try {
  		const result = await authorizationToken(params, mode);
  		// console.log('phoneLogin',result);
  		if (result.Data) {
  			const token = result.Data;
  			await dispatch('loginEnd', token);

  			return await dispatch('afterLoginAction', goHome);
  		}
  		return null;
  	} catch (error) {
  		return Promise.reject(error);
  	}
  },
	/**
	 * @description: 设置当前组织机构
	 */
	setOrganization: async function({
		state,
		commit,
		dispatch
	}, {
		organizationId,
		mode
	}) {
		try {
			const result = await setOrganization(organizationId, mode);
			if (result.Data) {
				const token = result.Data;
				await dispatch('loginEnd', token);

				return await dispatch('afterLoginAction');
			}
			return null;
		} catch (error) {
			throw error;
		}
	},
	/**
	 * @description: 验证登录（Check Login）
	 */
	checkLogin: async function({
		state,
		commit,
		dispatch
	}, {
		params,
		goHome,
		mode
	}) {
		try {
			const result = await checkLogin(params, mode);
			if (result.Type === 200) {
				await dispatch('afterLoginAction', goHome);
			}
			return result.Type === 200;
		} catch (error) {
			return false;
		}
	},
	/**
	 * 登录后操作
	 * @param goHome 是否返回主页
	 * @returns 用户信息
	 */
	afterLoginAction: async function({
		state,
		commit,
		getters,
		dispatch
	}, goHome) {
		// console.log('afterLoginAction',{ goHome });
		if (!getters.getAccessToken) return null;
		// console.log('afterLoginAction',{ goHome, accessToken: getters.getAccessToken });
		// get user info
		const userInfo = await dispatch('getUserInfoAction');
		// console.log('afterLoginAction',{ goHome, accessToken: getters.getAccessToken, userInfo });

		// const permissionStore = usePermissionStore();
		// if (!permissionStore.isDynamicAddedRoute) {
		// 	const routes = await permissionStore.buildRoutesAction();
		// 	routes.forEach((route) => {
		// 		router.addRoute(route as unknown as RouteRecordRaw);
		// 	});
		// 	router.addRoute(PAGE_NOT_FOUND_ROUTE as unknown as RouteRecordRaw);
		// 	permissionStore.setDynamicAddedRoute(true);
		// }
		if (goHome === true) {
			const pages = getCurrentPages();
			// console.log('afterLoginAction', pages);
			if (pages && pages.length > 1) {
				// 存在上级页面，直接返回
				// console.log('afterLoginAction', '存在上级页面，直接返回');
				uni.navigateBack();
			} else {
				// 不存在上级页面，跳转到主页
				// console.log('afterLoginAction', '不存在上级页面，跳转到主页');
				uni.switchTab({
					url: '/pages/sys/home/index'
				});
			}
		}

		return userInfo;
	},
	/**
	 * 获取用户信息操作
	 * @returns 用户信息
	 */
	getUserInfoAction: async function({
		state,
		commit,
		dispatch
	}) {
		const userInfo = await dispatch('refreshUser');
		return userInfo;
	},
	/**
	 * @description: 注销（logout）
	 */
	logout: async function({
		state,
		commit,
		getters,
		dispatch
	}, goLogin = false) {
		// console.log('logout',goLogin);
		if (getters.getAccessToken) {
			try {
				await logout();
			} catch {
				console.log('注销Token失败');
			}
		}
		await dispatch('setToken', undefined);

		if (goLogin === true) {
			// 跳转去登录页
			const pages = getCurrentPages();
			let currentRoute = '';
			if (pages && pages.length > 0) {
				const currentPage = pages[pages.length - 1];
				if (currentPage.route) {
					currentRoute = currentPage.route;
				}
			}
			// console.log(currentPage);
			if (currentRoute !== 'pages/sys/login/agreement' && currentRoute !==
				'pages/sys/login/forgetPassword' &&
				currentRoute !== 'pages/sys/login/login' && currentRoute !== 'pages/sys/login/register' &&
				currentRoute !== 'pages/sys/login/setter') {
				// 保留当前页面，跳转到登录页
				uni.navigateTo({
					url: '/pages/sys/login/login',
					passedParams: {
						info: '已登出',
					},
				});
				// // 关闭所有页面，打开到登录页（这种方式貌似会让该页面扫描监听失效，暂注释）
				// uni.reLaunch({
				// 	url: '/pages/sys/login/login',
				// 	passedParams: {
				// 		info: '已登出',
				// 	},
				// });
			}
		}
	},
	/** 编辑用户信息 */
	profileEdit: async function({
		state,
		commit,
		dispatch
	}, {
		params,
		mode
	}) {
		try {
			const result = await profileEdit(params, mode);
			if (result.Type === 200) {
				const userInfo = await dispatch('refreshUser');
				return userInfo;
			} else {
				console.log('profileEdit-Error', result.Content);
				// throw new Error(result.Content);
			}
			return null;
		} catch (error) {
			throw error;
		}
	},
	/** 修改密码 */
	changePassword: async function({
		state,
		commit,
		dispatch
	}, {
		params,
		mode
	}) {
		try {
			const result = await changePassword(params, mode);
			if (result.Type === 200) {
				const userInfo = await dispatch('refreshUser');
				return userInfo;
			} else {
				console.log('changePassword-Error', result.Content);
				// throw new Error(result.Content);
			}
			return null;
		} catch (error) {
			throw error;
		}
	},
	/** 用户手机变更 */
	changeUserPhone: async function({
		state,
		commit,
		dispatch
	}, {
		params,
		mode
	}) {
		try {
			const result = await changeUserPhone(params, mode);
			if (result.Type === 200) {
				const userInfo = await dispatch('refreshUser');
				return userInfo;
			} else {
				console.log('changeUserPhone-Error', result.Content);
				// throw new Error(result.Content);
			}
			return null;
		} catch (error) {
			throw error;
		}
	},
	/**
	 * 登录完成后程序处理
	 * @param token JwtToken模型
	 */
	loginEnd: async function({
		state,
		commit,
		dispatch
	}, token) {
		// 设置Token
		await dispatch('setToken', token);
		//初始化SignalR连接
		await dispatch('connectSignalRHub');
	},
	/** 刷新用户信息 */
	refreshUser: async function({
		state,
		commit,
		dispatch
	}) {
		const profileDto = await profile();
		if (profileDto === undefined || profileDto === null) {
			uni.removeStorageSync(USER_INFO_KEY);
			return null;
		}
		const userInfo = {
			UserId: profileDto.UserId,
			UserName: profileDto.UserName,
			NickName: profileDto.NickName,
			Email: profileDto.Email,
			PhoneNumber: profileDto.PhoneNumber,
			Avatar: profileDto.Avatar,

			Gender: profileDto.Gender,
			Birthday: profileDto.Birthday,
			BloodType: profileDto.BloodType,
			Tag: profileDto.Tag,
			Title: profileDto.Title,
			Address: profileDto.Address,
			Profile: profileDto.Profile,
			Signature: profileDto.Signature,

			ChineseBirthday: profileDto.ChineseBirthday,
			Age: profileDto.Age,
			ZodiacSign: profileDto.ZodiacSign,
			StarSign: profileDto.StarSign,

			Remark: profileDto.Remark,
			IsAdmin: profileDto.IsAdmin,

			IsRefreshNext: profileDto.IsRefreshNext,

			Roles: profileDto.Roles,

			CurrentOrganization: profileDto.CurrentOrganization,
			CurrentDepartment: profileDto.CurrentDepartment,

			ExtendData: profileDto.ExtendData,
		};
		//处理用户头像
		if (userInfo.Avatar === undefined || userInfo.Avatar === null || userInfo.Avatar === '') {
			userInfo.Avatar = headerImg;
		}
		// userInfo.Avatar = handleFileLink(profileDto.Avatar);
		//设置用户
    await	dispatch('setUserInfo', userInfo);
		// 刷新角色（授权信息）
		//const roleList = userInfo.Roles.map((item) => item.Value) as string[];
		await dispatch('refreshAuthInfo');

		// TODO:获取及设置系统偏好设置项（可以通过远程Api的方式获取，建议封装成独立方法）
		// setPreferenceInfo({
		// 	Id: 1,
		// 	OrganizationId: userInfo?.CurrentOrganization?.Id ?
		// 		(userInfo.CurrentOrganization.Id as unknown as number) :
		// 		-1,
		// 	Initialized: true,
		// 	CEO: '',
		// 	CFO: '',
		// 	MainCurrencyId: 'CNY',
		// 	SysCurrencyId: 'CNY',
		// 	ExchangeQuotation: ExchangeQuotationEnum.DirectQuotation,
		// 	QuantityAccuracy: 4,
		// 	PriceAccuracy: 6,
		// 	AmountAccuracy: 2,
		// 	RateAccuracy: 4,
		// 	PercentageAccuracy: 4,
		// 	MeasureAccuracy: 4,
		// 	CompanyName: userInfo?.CurrentOrganization?.Id ? userInfo.CurrentOrganization.Id : '',
		// 	TaxpayerNumber: '',
		// 	CompanyAddr: '',
		// 	CompanyTel: '',
		// 	CompanyBank: '',
		// 	CompBakAccount: '',
		// });

		return userInfo;
	},
	/** 刷新授权信息 */
	refreshAuthInfo: async function({
		state,
		commit,
		getters,
		dispatch
	}) {
		const authInfoList = (await getAuthInfo('none')) || [];
		// 设置权限代码列表
		await dispatch('setPermCodeList', authInfoList);

		// 获取角色（授权信息）
		const roleList = getters.getRoleList || [];
		//对比字符串
		const authInfoListString = authInfoList.sort().toString();
		const roleListString = roleList.sort().toString();

		// console.log('refreshAuthInfo', { authInfoList, roleList });
		if (roleListString !== authInfoListString) {
			// 设置角色（授权信息）
			await dispatch('setRoleList', authInfoList);

			// 刷新菜单数据（refresh menu data）
			// const {
			// 	refreshMenu
			// } = usePermission();
			// await refreshMenu();
		}
	},
	/** 心跳业务 */
	viaHeartbeats: async function({
		state,
		commit,
		getters,
		dispatch
	}) {
		//启动网站时，如果存在jsonWebToken则刷新一次
		const token = getters.getToken;
		if (token) {
			const refreshToken = token.RefreshToken;
			if (refreshToken) {
				try {
					await dispatch('refreshToken', {
						refreshToken,
						mode: 'message'
					});
				} catch (err) {} finally {}
			}
		}
		// 每5秒检测AccessToken有效期，如过期则使用RefreshToken来刷新
		setInterval(async () => {
			// console.log('viaHeartbeats','尝试刷新AccessToken和RefreshToken');
			try {
				//尝试刷新AccessToken和RefreshToken
				// await dispatch('tryRefreshToken', 'message');
        await dispatch('tryRefreshToken');
			} catch (err) {} finally {}
		}, 5000);

		// 每30秒刷新授权信息
		try {
			//尝试刷新AccessToken和RefreshToken
			await dispatch('refreshAuthInfo');
		} catch (err) {} finally {}
		setInterval(async () => {
			// 刷新角色（授权信息）
			try {
				//尝试刷新AccessToken和RefreshToken
				await dispatch('refreshAuthInfo');
			} catch (err) {} finally {}
		}, 30000);
	},
	/**
	 * 尝试刷新AccessToken和RefreshToken，检测AccessToken有效期，如过期则使用RefreshToken来刷新
	 * @param mode 错误消息模型
	 */
	tryRefreshToken: async function({
		state,
		commit,
		getters,
		dispatch
	}, mode = 'none') {
		const token = getters.getToken;
		// console.log('tryRefreshToken', mode);
		if (token) {
			// const diff = Math.round((token.AccessTokenExpiresUtc - new Date().valueOf()) / 1000);
      const now = new Date();
      const seconds = now.valueOf();
      const accessTokenExpiresUtc = token.AccessTokenExpiresUtc ? Number(token.AccessTokenExpiresUtc) : 0;
      const diff = (accessTokenExpiresUtc - seconds) / 1000;
      // console.log('tryRefreshToken', { accessTokenExpiresUtc, seconds, diff });
      // 检测Token的有效期和当前时间相差小于300秒时，执行刷新Token，否则跳过
			if (diff > 300) {
				return;
			}
			const refreshToken = token.RefreshToken;
			if (refreshToken) {
				try {
					await dispatch('refreshToken', {
						refreshToken,
						mode
					});
				} catch (err) {} finally {}
			}
		}
	},
	/**
	 * 使用现在的RefreshToken刷新新的AccessToken与RefreshToken
	 * @param refreshToken 现有的RefreshToken
	 * @param mode 错误消息模型
	 */
	refreshToken: async function({
		state,
		commit,
		dispatch
	}, {
		refreshToken,
		mode = 'none'
	}) {
		try {
			// 使用RefreshToken刷新AccessToken
			const dto = {
				RefreshToken: refreshToken,
				GrantType: 'refresh_token'
			};
			const result = await tokenApi(dto, mode);
			const token = result.Data;
      // 设置Token
      await dispatch('setToken', token, false);
      //初始化SignalR连接
      await dispatch('connectSignalRHub');

			const userInfo = await dispatch('afterLoginAction');
			return userInfo;
		} catch (error) {
			//createMessage.error(error?.message);
			return null;
		}
	},
	/** 连接SignalR集线器 */
	connectSignalRHub: async function({
		state,
		commit,
		getters,
		dispatch
	}) {
		// //先断开连接，后重新设置
		// await dispatch('disconnectSignalRHub');

		// if (state.signalrHub !== null) {
		// 	//如果已经连接，则返回
		// 	if (
		// 		state.signalrHub.state === signalR.HubConnectionState.Connected ||
		// 		state.signalrHub.state === signalR.HubConnectionState.Connecting ||
		// 		state.signalrHub.state === signalR.HubConnectionState.Reconnecting
		// 	) {
		// 		return;
		// 	} else {
		// 		state.signalrHub = null;
		// 	}
		// }

		// let signalrHubUrl = '';
		// const {
		// 	signalrUrl,
		// 	signalrPrefix,
		// 	signalrServerTimeout,
		// 	signalrKeepAliveInterval
		// } =
		// useGlobSetting();
		// if (signalrPrefix !== undefined && signalrPrefix !== null && signalrPrefix !== '') {
		// 	signalrHubUrl = signalrPrefix.startsWith('/') ? signalrPrefix : `/${signalrPrefix}`;
		// }
		// if (signalrUrl !== undefined && signalrUrl !== null && signalrUrl !== '') {
		// 	signalrHubUrl = `${signalrUrl}${signalrHubUrl}`;
		// }
		// //SignalR
		// state.signalrHub = new signalR.HubConnectionBuilder()
		// 	//服务器地址：本地站点可以直接写“/xxx”。JWT验证码：不带Bearer
		// 	.withUrl(signalrHubUrl, {
		// 		accessTokenFactory: () => getters.getAccessToken
		// 	})
		// 	//默认不会自动重连，需手动调用 withAutomaticReconnect
		// 	//如果不带任何参数，withAutomaticReconnect 会配置客户端在每一次重连尝试之前，分别等待0，2，10，30秒，如果四次重连均失败，那么连接便会停止。
		// 	//如果配置了自动重连，在开始每一次重连尝试之前，HubConnection 都会变为 HubConnectionState.Reconnecting 状态并触发它的onreconnecting 回调。
		// 	//而如果没有配置HubConnection 为自动重连，此时（连接断开时）HubConnection 的状态会变为Disconnected 并触发它的onclose 回调。
		// 	//这就提供了一个时机来警告用户连接已经丢失，并禁用掉相关的UI元素。
		// 	.withAutomaticReconnect({
		// 		nextRetryDelayInMilliseconds: (retryContext) => {
		// 			if (retryContext.elapsedMilliseconds < 60000) {
		// 				// 如果到目前为止我们重新连接的时间不到60秒，在下一次重新连接尝试之前的0到10秒之间。
		// 				return Math.random() * 10000;
		// 			} else {
		// 				// 如果到目前为止重新连接的时间超过60秒，请停止重新连接。
		// 				return null;
		// 			}
		// 		},
		// 	})
		// 	.build();
		// if (signalrServerTimeout && signalrServerTimeout > 0) {
		// 	state.signalrHub.serverTimeoutInMilliseconds = signalrServerTimeout;
		// }
		// if (signalrKeepAliveInterval && signalrKeepAliveInterval > 0) {
		// 	state.signalrHub.keepAliveIntervalInMilliseconds = signalrKeepAliveInterval;
		// }

		// // state.signalrHub.onreconnecting(async (error) => {
		// //   console.log('监听到正在连接SignalR', error);
		// // });
		// // state.signalrHub.onreconnected(async (connectionId) => {
		// //   console.log('监听到连接SignalR成功', connectionId);
		// // });
		// state.signalrHub.onclose(async (error) => {
		// 	console.log('监听到连接SignalR关闭', error);
		// 	state.signalrHub = null;
		// });

		// // state.signalrHub.on('AAA', (msg: string) => {
		// //   const { createMessage } = useMessage();
		// //   createMessage.success(msg);
		// // });

		// //如果已经断开连接，则连接
		// try {
		// 	if (
		// 		state.signalrHub.state === signalR.HubConnectionState.Disconnected ||
		// 		state.signalrHub.state === signalR.HubConnectionState.Disconnecting
		// 	) {
		// 		await state.signalrHub.start();
		// 	}
		// 	// state.signalrHub.on('BBB', (msg: string) => {
		// 	//   const { createMessage } = useMessage();
		// 	//   createMessage.success(msg);
		// 	// });
		// } catch (error: any) {
		// 	console.log('连接SignalR失败', error?.message);
		// 	state.signalrHub = null;
		// }
	},
	/** 断开连接SignalR集线器 */
	disconnectSignalRHub: async function({
		state,
		commit,
		dispatch
	}) {
		// //SignalR
		// if (state.signalrHub !== null) {
		// 	//如果已经连接，则断开
		// 	if (
		// 		state.signalrHub.state === signalR.HubConnectionState.Connected ||
		// 		state.signalrHub.state === signalR.HubConnectionState.Connecting ||
		// 		state.signalrHub.state === signalR.HubConnectionState.Reconnecting
		// 	) {
		// 		await state.signalrHub.stop();
		// 	}
		// }
		// state.signalrHub = null;
	},
}
